package com.example.eeuse.exception;

import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;

import javax.validation.ConstraintViolationException;
import org.springframework.web.bind.MethodArgumentNotValidException;

import java.util.List;

@RestControllerAdvice
public class GlobalExceptionHandler {

    @ExceptionHandler(ConstraintViolationException.class)
    public ResponseEntity<Object> handleConstraintViolationException(ConstraintViolationException ex) {
        // 返回详细的验证错误信息
        return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(ex.getMessage());
    }

    @ExceptionHandler(MethodArgumentNotValidException.class)
    public ResponseEntity<Object> handleMethodArgumentNotValidException(MethodArgumentNotValidException ex) {
        // 获取验证错误信息
        List<ObjectError> errors = ex.getBindingResult().getAllErrors();
        StringBuilder message = new StringBuilder();
        for (ObjectError error : errors) {
            FieldError fieldError = (FieldError) error;
            message.append(fieldError.getField()).append(": ").append(fieldError.getDefaultMessage()).append("\n");
        }
        return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(message.toString());
    }
    // 捕获 HttpMessageNotReadableException 异常
    @ExceptionHandler(HttpMessageNotReadableException.class)
    public ResponseEntity<String> handleHttpMessageNotReadableException(HttpMessageNotReadableException ex) {
        // 可以根据需要处理异常信息，例如返回自定义错误消息
        String errorMessage = "请求体解析失败：格式不正确或者字段不匹配";
        // 返回 400 状态码和错误信息
        return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(errorMessage);
    }
}
